

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/images/base.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Airfe">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文分析了axios的部分关键源码。">
<meta property="og:type" content="article">
<meta property="og:title" content="Axios部分源码解读">
<meta property="og:url" content="https://airfe.gitee.io/blog/2023/06/19/Axios%E9%83%A8%E5%88%86%E6%BA%90%E7%A0%81%E8%A7%A3%E8%AF%BB/index.html">
<meta property="og:site_name" content="Airfe的博客">
<meta property="og:description" content="本文分析了axios的部分关键源码。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/Axios.jpg">
<meta property="article:published_time" content="2023-06-19T00:00:00.000Z">
<meta property="article:modified_time" content="2023-06-19T00:00:00.000Z">
<meta property="article:author" content="Airfe">
<meta property="article:tag" content="Axios">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/Axios.jpg">
  
  
  
    <meta name="referrer" content="no-referrer" />
  
  <title>Axios部分源码解读 - Airfe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"airfe.gitee.io","root":"/blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"699a5d71ac7179b23874a59b0666a6f6","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","app_key":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?699a5d71ac7179b23874a59b0666a6f6";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Airfe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/images/bg.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Axios部分源码解读"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-06-19 08:00" pubdate>
          2023年06月19日
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          6.3k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          53 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Axios部分源码解读</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="Axios"><a href="#Axios" class="headerlink" title="Axios"></a>Axios</h1><p>基于promise的http客户端，可以在浏览器和node.js两个环境中运行。</p>
<p>浏览器端借助于Axios可以向服务端发送Ajax请求，node.js中可以用axios向远端服务发送http请求。</p>
<h2 id="主要特性"><a href="#主要特性" class="headerlink" title="主要特性"></a>主要特性</h2><ul>
<li>基于 Promise</li>
<li>支持浏览器和 node.js环境</li>
<li>可添加请求、响应拦截器和转换请求和响应数据</li>
<li>请求可以取消、中断</li>
<li>自动转换 JSON 数据</li>
<li>客户端支持防范 XSRF</li>
</ul>
<h2 id="源码目录结构"><a href="#源码目录结构" class="headerlink" title="源码目录结构"></a>源码目录结构</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs js">├── /dist/ # 项目输出目录<br>├── /lib/ # 项目源码目录<br>│ ├── /adapters/ # 定义请求的适配器 xhr、http<br>│ │ ├── http.<span class="hljs-property">js</span> # 实现 http 适配器(包装 http 包)<br>│ │ └── xhr.<span class="hljs-property">js</span> # 实现 xhr 适配器(包装 xhr 对象)<br>│ ├── /cancel/ # 定义取消功能<br>│ ├── /core/ # 一些核心功能<br>│ │ ├── <span class="hljs-title class_">Axios</span>.<span class="hljs-property">js</span> # axios 的核心主类<br>│ │ ├── dispatchRequest.<span class="hljs-property">js</span> # 用来调用 http 请求适配器方法发送请求的函数<br>│ │ ├── <span class="hljs-title class_">InterceptorManager</span>.<span class="hljs-property">js</span> # 拦截器的管理器<br>│ │ └── settle.<span class="hljs-property">js</span> # 根据 http 响应状态，改变 <span class="hljs-title class_">Promise</span> 的状态<br>│ ├── /helpers/ # 一些辅助方法<br>│ ├── axios.<span class="hljs-property">js</span> # 对外暴露接口<br>│ ├── defaults.<span class="hljs-property">js</span> # axios 的默认配置<br>│ └── utils.<span class="hljs-property">js</span> # 公用工具<br>├── package.<span class="hljs-property">json</span> # 项目信息<br>├── index.<span class="hljs-property">d</span>.<span class="hljs-property">ts</span> # 配置 <span class="hljs-title class_">TypeScript</span> 的声明文件<br>└── index.<span class="hljs-property">js</span> # 入口文件<br></code></pre></td></tr></table></figure>

<h2 id="axios对象创建过程模拟实现"><a href="#axios对象创建过程模拟实现" class="headerlink" title="axios对象创建过程模拟实现"></a>axios对象创建过程模拟实现</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><code class="hljs js">&lt;script&gt;<br>        <span class="hljs-comment">// 构造函数</span><br>        <span class="hljs-keyword">function</span> <span class="hljs-title function_">Axios</span>(<span class="hljs-params">config</span>) &#123;<br>            <span class="hljs-comment">// 初始化</span><br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">defaults</span> = config; <span class="hljs-comment">// 为了创建default默认属性</span><br>            <span class="hljs-variable language_">this</span>.<span class="hljs-property">intercepters</span> = &#123;<br>                <span class="hljs-attr">request</span>: &#123;&#125;,<br>                <span class="hljs-attr">response</span>: &#123;&#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-comment">// 原型添加相关的方法</span><br>        <span class="hljs-title class_">Axios</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">request</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">config</span>) &#123;<br>            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;发送AJAX请求 请求的类型为&#x27;</span> ,config.<span class="hljs-property">method</span>);<br>        &#125;<br>        <span class="hljs-title class_">Axios</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">get</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">config</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">request</span>(&#123;<span class="hljs-attr">method</span>:<span class="hljs-string">&#x27;GET&#x27;</span>&#125;);<br>        &#125;<br>        <span class="hljs-title class_">Axios</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">post</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">config</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">request</span>(&#123;<span class="hljs-attr">method</span>:<span class="hljs-string">&#x27;POST&#x27;</span>&#125;);<br>        &#125;<br>        <span class="hljs-comment">// 声明函数</span><br>        <span class="hljs-keyword">function</span> <span class="hljs-title function_">createInstance</span>(<span class="hljs-params">config</span>) &#123;<br>            <span class="hljs-comment">// 实例化一个对象</span><br>            <span class="hljs-keyword">let</span> context = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Axios</span>(config); <span class="hljs-comment">// 此时可以context.get() context.post() 但是不能当做函数使用即context()</span><br>            <span class="hljs-comment">// 创建请求函数,context.request(), 此时的this指向context的this</span><br>            <span class="hljs-keyword">let</span> instance = <span class="hljs-title class_">Axios</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">request</span>.<span class="hljs-title function_">bind</span>(context); <span class="hljs-comment">// instanc 是一个函数，并且可以instance(&#123;&#125;),此时还不能使用instance.get</span><br>            <span class="hljs-comment">// 将Axios.prototype对象中的方法添加到instance函数对象中</span><br>            <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">keys</span>(<span class="hljs-title class_">Axios</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>).<span class="hljs-title function_">forEach</span>(<span class="hljs-function"><span class="hljs-params">key</span> =&gt;</span> &#123;<br>                instance[key] = <span class="hljs-title class_">Axios</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>[key].<span class="hljs-title function_">bind</span>(context);  <span class="hljs-comment">// 给instance挂载,并使this始终指向context</span><br>            &#125;)<br>            <span class="hljs-comment">// 为instance函数对象添加属性default与intercepters</span><br>            <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">keys</span>(context).<span class="hljs-title function_">forEach</span>(<span class="hljs-function"><span class="hljs-params">key</span> =&gt;</span> &#123;<br>                instance[key] = context[key];  <span class="hljs-comment">// 给instance挂载,并使this始终指向context</span><br>            &#125;)<br>            <span class="hljs-keyword">return</span> instance<br>        &#125;<br>        <span class="hljs-keyword">let</span> axios = <span class="hljs-title function_">createInstance</span>();<br>        <span class="hljs-comment">// 发送请求,既可以当成函数使用，也可以当做对象调方法使用</span><br>        <span class="hljs-comment">// axios.(&#123;method:&#x27;GET&#x27;&#125;)</span><br>        axios.<span class="hljs-title function_">get</span>(&#123;&#125;)<br>        axios.<span class="hljs-title function_">post</span>(&#123;&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="核心请求方法"><a href="#核心请求方法" class="headerlink" title="核心请求方法"></a>核心请求方法</h2><p>Axios.prototype.request可以说是整个axios请求的核心骨架，这里面主要做了对不同config的适配，以及关键的核心链式调用实现。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title class_">Axios</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">request</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">request</span>(<span class="hljs-params">config</span>) &#123;<br>  <span class="hljs-comment">// 判断参数类型 以支持不同的请求形式axios(&#x27;url&#x27;,config) / axios(config)</span><br>  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> config === <span class="hljs-string">&#x27;string&#x27;</span>) &#123;<br>    config = <span class="hljs-variable language_">arguments</span>[<span class="hljs-number">1</span>] || &#123;&#125;;<br>    config.<span class="hljs-property">url</span> = <span class="hljs-variable language_">arguments</span>[<span class="hljs-number">0</span>];<br>  &#125; <span class="hljs-keyword">else</span> &#123;<br>    config = config || &#123;&#125;;<br>  &#125;<br>	<span class="hljs-comment">// 配置合并默认配置</span><br>  config = <span class="hljs-title function_">mergeConfig</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">defaults</span>, config);<br><br>  <span class="hljs-comment">// 转化请求的方法 转化为小写</span><br>  <span class="hljs-keyword">if</span> (config.<span class="hljs-property">method</span>) &#123;<br>    config.<span class="hljs-property">method</span> = config.<span class="hljs-property">method</span>.<span class="hljs-title function_">toLowerCase</span>();<br>  &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">defaults</span>.<span class="hljs-property">method</span>) &#123;<br>    config.<span class="hljs-property">method</span> = <span class="hljs-variable language_">this</span>.<span class="hljs-property">defaults</span>.<span class="hljs-property">method</span>.<span class="hljs-title function_">toLowerCase</span>();<br>  &#125; <span class="hljs-keyword">else</span> &#123;<br>    config.<span class="hljs-property">method</span> = <span class="hljs-string">&#x27;get&#x27;</span>;<br>  &#125;<br><br>  <span class="hljs-keyword">var</span> transitional = config.<span class="hljs-property">transitional</span>;<br>	<br>  <span class="hljs-keyword">if</span> (transitional !== <span class="hljs-literal">undefined</span>) &#123;<br>    <span class="hljs-comment">// 针对性配置检测 1.0.0版本以后 transitional配置将移除 （好奇目前距离1.0版本好像距离很远，不知为何）</span><br>    validator.<span class="hljs-title function_">assertOptions</span>(transitional, &#123;<br>      <span class="hljs-attr">silentJSONParsing</span>: validators.<span class="hljs-title function_">transitional</span>(validators.<span class="hljs-property">boolean</span>, <span class="hljs-string">&#x27;1.0.0&#x27;</span>),<br>      <span class="hljs-attr">forcedJSONParsing</span>: validators.<span class="hljs-title function_">transitional</span>(validators.<span class="hljs-property">boolean</span>, <span class="hljs-string">&#x27;1.0.0&#x27;</span>),<br>      <span class="hljs-attr">clarifyTimeoutError</span>: validators.<span class="hljs-title function_">transitional</span>(validators.<span class="hljs-property">boolean</span>, <span class="hljs-string">&#x27;1.0.0&#x27;</span>)<br>    &#125;, <span class="hljs-literal">false</span>);<br>  &#125;<br>	<br>  <span class="hljs-comment">// ........ 核心链式调用</span><br>&#125;;<br></code></pre></td></tr></table></figure>

<h2 id="拦截器实现"><a href="#拦截器实现" class="headerlink" title="拦截器实现"></a>拦截器实现</h2><p>拦截器在<code>axios.create</code>中<code>createInstance</code>去<code>new Axios</code>实例时构构建出来的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">Axios</span>(<span class="hljs-params">instanceConfig</span>) &#123;<br>  <span class="hljs-variable language_">this</span>.<span class="hljs-property">defaults</span> = instanceConfig;<br>  这里创建的请求和响应拦截器 通过统一的类构造出来的<br>  <span class="hljs-variable language_">this</span>.<span class="hljs-property">interceptors</span> = &#123;<br>    <span class="hljs-attr">request</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">InterceptorManager</span>(),<br>    <span class="hljs-attr">response</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">InterceptorManager</span>()<br>  &#125;;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>进入&#x2F;core&#x2F;InterceptorManager.js中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">InterceptorManager</span>(<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-variable language_">this</span>.<span class="hljs-property">handlers</span> = [];<br>&#125;<br><span class="hljs-comment">// 添加拦截器 添加成功、失败回调</span><br><span class="hljs-title class_">InterceptorManager</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">use</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">use</span>(<span class="hljs-params">fulfilled, rejected, options</span>) &#123;<br>  <span class="hljs-variable language_">this</span>.<span class="hljs-property">handlers</span>.<span class="hljs-title function_">push</span>(&#123;<br>    <span class="hljs-attr">fulfilled</span>: fulfilled,<br>    <span class="hljs-attr">rejected</span>: rejected,<br>    <span class="hljs-attr">synchronous</span>: options ? options.<span class="hljs-property">synchronous</span> : <span class="hljs-literal">false</span>,<br>    <span class="hljs-attr">runWhen</span>: options ? options.<span class="hljs-property">runWhen</span> : <span class="hljs-literal">null</span><br>  &#125;);<br>  <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">handlers</span>.<span class="hljs-property">length</span> - <span class="hljs-number">1</span>;<br>&#125;;<br><br><span class="hljs-comment">// 注销指定拦截器</span><br><span class="hljs-title class_">InterceptorManager</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">eject</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">eject</span>(<span class="hljs-params">id</span>) &#123;<br>  <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">handlers</span>[id]) &#123;<br>    <span class="hljs-variable language_">this</span>.<span class="hljs-property">handlers</span>[id] = <span class="hljs-literal">null</span>;<br>  &#125;<br>&#125;;<br><br><span class="hljs-comment">// 遍历执行</span><br><span class="hljs-title class_">InterceptorManager</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">forEach</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">forEach</span>(<span class="hljs-params">fn</span>) &#123;<br>  utils.<span class="hljs-title function_">forEach</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">handlers</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">forEachHandler</span>(<span class="hljs-params">h</span>) &#123;<br>    <span class="hljs-comment">// 确定没被eject注销 才执行</span><br>    <span class="hljs-keyword">if</span> (h !== <span class="hljs-literal">null</span>) &#123;<br>      <span class="hljs-title function_">fn</span>(h);<br>    &#125;<br>  &#125;);<br>&#125;;<br><br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-title class_">InterceptorManager</span>;<br></code></pre></td></tr></table></figure>

<h2 id="dispatchRequest"><a href="#dispatchRequest" class="headerlink" title="dispatchRequest"></a>dispatchRequest</h2><ul>
<li><p>处理请求头config配置</p>
</li>
<li><p>调用<code>adapter</code>适配器发起真正的请求，针对浏览器环境发起ajax请求，node环境发起http请求</p>
</li>
<li><p>构造响应数据， 会自动转换 JSON 数据</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><code class="hljs js"> <span class="hljs-keyword">function</span> <span class="hljs-title function_">dispatchRequest</span>(<span class="hljs-params">config</span>) &#123;<br>	<span class="hljs-comment">// 提前取消请求</span><br>  <span class="hljs-title function_">throwIfCancellationRequested</span>(config);<br><br>  <span class="hljs-comment">// 赋个默认值</span><br>  config.<span class="hljs-property">headers</span> = config.<span class="hljs-property">headers</span> || &#123;&#125;;<br><br>  <span class="hljs-comment">// 转换数据</span><br>  config.<span class="hljs-property">data</span> = transformData.<span class="hljs-title function_">call</span>(<br>    config,<br>    config.<span class="hljs-property">data</span>,<br>    config.<span class="hljs-property">headers</span>,<br>    config.<span class="hljs-property">transformRequest</span><br>  );<br><br>  <span class="hljs-comment">// 合并headers配置</span><br>  config.<span class="hljs-property">headers</span> = utils.<span class="hljs-title function_">merge</span>(<br>    config.<span class="hljs-property">headers</span>.<span class="hljs-property">common</span> || &#123;&#125;,<br>    config.<span class="hljs-property">headers</span>[config.<span class="hljs-property">method</span>] || &#123;&#125;,<br>    config.<span class="hljs-property">headers</span><br>  );<br>  <span class="hljs-comment">// 删除多余的被合并过的数据</span><br>  utils.<span class="hljs-title function_">forEach</span>(<br>    [<span class="hljs-string">&#x27;delete&#x27;</span>, <span class="hljs-string">&#x27;get&#x27;</span>, <span class="hljs-string">&#x27;head&#x27;</span>, <span class="hljs-string">&#x27;post&#x27;</span>, <span class="hljs-string">&#x27;put&#x27;</span>, <span class="hljs-string">&#x27;patch&#x27;</span>, <span class="hljs-string">&#x27;common&#x27;</span>],<br>    <span class="hljs-keyword">function</span> <span class="hljs-title function_">cleanHeaderConfig</span>(<span class="hljs-params">method</span>) &#123;<br>      <span class="hljs-keyword">delete</span> config.<span class="hljs-property">headers</span>[method];<br>    &#125;<br>  );<br>  <span class="hljs-comment">// 适配器 axios是可以支持node端也支持浏览器端的 </span><br>  <span class="hljs-keyword">var</span> adapter = config.<span class="hljs-property">adapter</span> || defaults.<span class="hljs-property">adapter</span>;<br>  <span class="hljs-comment">// 执行请求</span><br>  <span class="hljs-keyword">return</span> <span class="hljs-title function_">adapter</span>(config).<span class="hljs-title function_">then</span>(<span class="hljs-keyword">function</span> <span class="hljs-title function_">onAdapterResolution</span>(<span class="hljs-params">response</span>) &#123;<br>    <span class="hljs-comment">// 提前取消请求情况</span><br>    <span class="hljs-title function_">throwIfCancellationRequested</span>(config);<br>    <span class="hljs-comment">// 做数据转换</span><br>    response.<span class="hljs-property">data</span> = transformData.<span class="hljs-title function_">call</span>(<br>      config,<br>      response.<span class="hljs-property">data</span>,<br>      response.<span class="hljs-property">headers</span>,<br>      config.<span class="hljs-property">transformResponse</span><br>    );<br>    <span class="hljs-keyword">return</span> response;<br>  &#125;, <span class="hljs-keyword">function</span> <span class="hljs-title function_">onAdapterRejection</span>(<span class="hljs-params">reason</span>) &#123;<br>    <span class="hljs-keyword">if</span> (!<span class="hljs-title function_">isCancel</span>(reason)) &#123;<br>      <span class="hljs-title function_">throwIfCancellationRequested</span>(config);<br>      <span class="hljs-comment">// 做数据转换</span><br>      <span class="hljs-keyword">if</span> (reason &amp;&amp; reason.<span class="hljs-property">response</span>) &#123;<br>        reason.<span class="hljs-property">response</span>.<span class="hljs-property">data</span> = transformData.<span class="hljs-title function_">call</span>(<br>          config,<br>          reason.<span class="hljs-property">response</span>.<span class="hljs-property">data</span>,<br>          reason.<span class="hljs-property">response</span>.<span class="hljs-property">headers</span>,<br>          config.<span class="hljs-property">transformResponse</span><br>        );<br>      &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(reason);<br>  &#125;);<br>&#125;;<br><br></code></pre></td></tr></table></figure>

<h2 id="适配器adapter"><a href="#适配器adapter" class="headerlink" title="适配器adapter"></a>适配器adapter</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">getDefaultAdapter</span>(<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-keyword">var</span> adapter;<br>  <span class="hljs-comment">// 判断XMLHttpRequest对象是否存在 存在则代表为浏览器环境</span><br>  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-title class_">XMLHttpRequest</span> !== <span class="hljs-string">&#x27;undefined&#x27;</span>) &#123;<br>    <span class="hljs-comment">// For browsers use XHR adapter</span><br>    adapter = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./adapters/xhr&#x27;</span>);<br>    <span class="hljs-comment">// node环境 使用原生http发起请求</span><br>  &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> process !== <span class="hljs-string">&#x27;undefined&#x27;</span> &amp;&amp; <span class="hljs-title class_">Object</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">toString</span>.<span class="hljs-title function_">call</span>(process) === <span class="hljs-string">&#x27;[object process]&#x27;</span>) &#123;<br>    adapter = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;./adapters/http&#x27;</span>);<br>  &#125;<br>  <span class="hljs-keyword">return</span> adapter;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>.&#x2F;adapters&#x2F;xhr.js 则是对原生ajax <code>XMLHttpRequest</code>对象的的封装,.&#x2F;adapters&#x2F;http.js 则是对node <code>http</code>模块的封装，也会针对https做相应处理。具体封装细节各种边界细节情况都做了特殊处理 ，因为我们日常还是在浏览器端使用比较多，简单对<code>xhr</code>的封装源码做些整体。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/" class="category-chain-item">前端技术栈</a>
  
  
    <span>></span>
    
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/js/" class="category-chain-item">js</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/Axios/">#Axios</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Axios部分源码解读</div>
      <div>https://airfe.gitee.io/blog/2023/06/19/Axios部分源码解读/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Airfe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年6月19日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2023/06/22/Vue%E5%9F%BA%E7%A1%80/" title="Vue基础知识">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Vue基础知识</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2023/06/17/Ajax/" title="Ajax">
                        <span class="hidden-mobile">Ajax</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appKey":"P5fzMTGSJIoTaGvmgzsUHeNZ","path":"window.location.pathname","placeholder":"发表你的看法吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"appid":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appkey":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com"},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
        <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数</span> <span id="times">载入时分秒</span> <script src="js/duration.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      蜀ICP备2023008943号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=https://beian.miit.gov.cn/"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="" srcset="/blog/img/loading.gif" lazyload data-original="/blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body>
</html>
